package com.stx.action;


import java.util.ArrayList;
import java.util.Date;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.stx.entity.User;
import com.stx.service.UserService;
import com.stx.util.MD5_Test;

public class RegisterAction extends ActionSupport {

	private User user;
	private UserService us;
	private String yzm;
	
	public String getYzm() {
		return yzm;
	}
	public void setYzm(String yzm) {
		this.yzm = yzm;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public UserService getUs() {
		return us;
	}
	public void setUs(UserService us) {
		this.us = us;
	}
	/*
	 * 先校验了验证码，
	 * 接着判断用户是否已经注册
	 * 设置用户的创建时间和 用户类型
	 * 用户的密码简单加密==================
	 * */
	public String addUser(){
		HttpSession session=ServletActionContext.getRequest().getSession();
		String jiaoyan=(String) session.getAttribute("img");
		System.out.println(jiaoyan);
		if(!jiaoyan.equals(yzm)){
			addActionError("验证码输入错误");
			return "failure";
		}
		if(us.getUser(user).size()!=0){
			addActionError("此用户已经注册");
			return "failure";
		}else{
		    user.setUs_type(5);
		    user.setUs_createtime(new Date());
		    user.setUs_image("images/user_normal.jpg");
		    user.setUs_password(MD5_Test.MD5(user.getUs_password()));
			us.addUser(user);
			return "success";
		}
		
	}
	/*
	 * 用户的登陆 校验用户名跟密码
	 * 设置session
	 * */
	public String findUser(){
		if(user==null){
			addActionError("请正确操作");
			return "failure";
		}else{
			user.setUs_password(MD5_Test.MD5(user.getUs_password()));
		}
		ArrayList<User>userList=(ArrayList<User>) us.findUser(user);
		if(userList.size()==0){
			addActionError("用户名或密码错误");
			return "failure";
		}else{
			ServletActionContext.getRequest().getSession().setAttribute("user",userList.get(0));
			return "success";
		}
	}
	/*
	 * 管理员的登陆 校验用户名跟密码
	 * 设置session
	 * */
	public String findAdminUser(){
		if(user==null){
			addActionError("对不起你没有权限");
			return "failure";
		}else{
			user.setUs_password(MD5_Test.MD5(user.getUs_password()));
		ArrayList<User>userList=(ArrayList<User>) us.findUser(user);
		if(userList.size()==0){
			addActionError("用户名或密码错误");
			return "failure";
		}else{
			if(userList.get(0).getUs_type()==5){
				addActionError("对不起你没有权限");
				return "failure";
			}else{
			ServletActionContext.getRequest().getSession().setAttribute("admin",userList.get(0));
			return "success";
			}
		}
		}
	}
}
